package com.ffyc.resale.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ffyc.resale.dao.AdminDao;
import com.ffyc.resale.dao.CarouselDao;
import com.ffyc.resale.dao.UserDao;
import com.ffyc.resale.model.Account;
import com.ffyc.resale.model.Admin;
import com.ffyc.resale.model.User;
import com.ffyc.resale.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminService{
    @Autowired
    AdminDao adminDao;
    public Account login(Account account) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("email",account.getEmail()).eq("password", account.getPassword());
        Admin admin = adminDao.selectOne(wrapper);
        if(admin==null){
            return null;
        }
        String token = JWTUtil.getToken(admin);
        admin.setToken(token);
        System.out.println(admin);
        admin.setRole("ADMIN");
        return admin;
    }

    public Admin profile(String adminToken) {
        Integer id = JWTUtil.id(adminToken);
        return adminDao.selectById(id);
    }

    public void updateProfile(String adminToken, Admin admin) {
        Integer id = JWTUtil.id(adminToken);
        admin.setId(id);
        adminDao.updateById(admin);
    }

    public boolean changePassword(String adminToken, Account account) {
        if (!account.getNewPassword().equals(account.getConfirmPassword())){
            return false;
        }
        Integer id = JWTUtil.id(adminToken);
        if(!adminDao.selectById(id).getPassword().equals(account.getPassword())){
            return false;
        }
        Admin admin = new Admin();
        admin.setId(id);
        admin.setPassword(account.getNewPassword());
        adminDao.updateById(admin);
        return true;
    }
}
